package com.google.jessewilson.codesearch.intellij;

import com.google.jessewilson.codesearch.util.PushProvider;
import com.google.jessewilson.codesearch.api.QueryRunner;
import com.google.jessewilson.codesearch.ide.DefaultQueryRunner;
import com.google.inject.*;

import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.editor.Editor;

/**
 * Search for code...
 *
 * @author jessewilson
 */
public class CodeSearch extends AnAction {

  public static final String CODE_SEARCH_WINDOW_ID = "Code Search";

  @Inject private PushProvider<Project> projectPushProvider;
  @Inject private PushProvider<QueryRunner> queryRunnerProvider;
  @Inject private PushProvider<Editor> editorPushProvider;
  @Inject private Provider<CodeSearchRunner> codeSearchActionHandlerProvider;
  @Inject private Provider<DefaultQueryRunner> defaultQueryRunnerProvider;

  public CodeSearch() {
    CodeSearchInjector.inject(this);
  }

  public void actionPerformed(final AnActionEvent actionEvent) {
    Project project = IntelliJUtils.projectFor(actionEvent);
    Editor editor = IntelliJUtils.editorFor(actionEvent);

    // can't search without a project
    if (project == null) {
      return;
    }

    projectPushProvider.push(project);
    queryRunnerProvider.push(defaultQueryRunnerProvider.get());
    editorPushProvider.push(editor);
    try {
      codeSearchActionHandlerProvider.get().execute(IntelliJUtils.fileFor(actionEvent));
    } finally {
      projectPushProvider.pop();
      queryRunnerProvider.pop();
      editorPushProvider.pop();
    }
  }
}